package com.kyc.kycxkplaygame.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.alipay.sdk.app.PayTask;
import com.kyc.kycxkplaygame.R;
import com.kyc.kycxkplaygame.alipay.AuthResult;
import com.kyc.kycxkplaygame.alipay.OrderInfoUtil2_0;
import com.kyc.kycxkplaygame.alipay.PayResult;
import com.kyc.kycxkplaygame.dbutils.GetPropLevelUtils;
import com.kyc.kycxkplaygame.dbutils.IntImp.AlasbusyIApi;
import com.kyc.kycxkplaygame.dbutils.inter.HttpQuestResultListener;
import com.kyc.kycxkplaygame.entity.PropsCode;
import com.kyc.kycxkplaygame.util.ConstactUtil;
import com.kyc.kycxkplaygame.util.TimeUtil;
import es.dmoral.toasty.Toasty;

import java.util.Map;

import static com.kyc.kycxkplaygame.util.ConstactUtil.*;


public class PropsBuyActivity extends Activity implements View.OnClickListener, HttpQuestResultListener {

    private ImageView daoju_image;
    private TextView price;
    private EditText buy_num;
    private ImageView buy_jian;
    private ImageView buy_jia;
    private ImageView sure_buy;
    private ImageView buy_delete;
    private String daoju;
    private String djName = "";


    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ConstactUtil.SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Log.i("TAG","resultStatus === " + resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(PropsBuyActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        if(daoju.equals("zhandan")) {
                            Intent intent = new Intent(PropsBuyActivity.this,GameActivity.class);
                            intent.putExtra("num",buy_num.getText().toString());
                            setResult(200,intent);
                            PropsBuyActivity.this.finish();
                        }else if(daoju.equals("tishi")) {
                            Intent intent = new Intent(PropsBuyActivity.this,GameActivity.class);
                            intent.putExtra("num",buy_num.getText().toString());
                            setResult(201,intent);
                            PropsBuyActivity.this.finish();
                        }else if(daoju.equals("times")){
                            Intent intent = new Intent(PropsBuyActivity.this,GameActivity.class);
                            intent.putExtra("num",buy_num.getText().toString());
                            setResult(202,intent);
                            PropsBuyActivity.this.finish();
                        }
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PropsBuyActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        //onBackPressed();
                    }
                    break;
                }
                case ConstactUtil.SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(PropsBuyActivity.this,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(PropsBuyActivity.this,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
                        //onBackPressed();

                    }
                    break;
                }
                default:
                    break;
            }
        };
    };
    private String propNum;
    private TextView price_grape;
    private TextView prop_grape_txt;
    private int num;
    private AlasbusyIApi alasbusyIApi;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setFinishOnTouchOutside(false);
        //EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX); //沙箱环境
        setContentView(R.layout.activity_props_buy);
        Window window = getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.alpha = 1f;
        window.setAttributes(layoutParams);
        Intent intent = getIntent();
        daoju = intent.getStringExtra("daoju");

        initView();
    }

    private void initView() {
        daoju_image = (ImageView) findViewById(R.id.daoju_image);
        price = (TextView) findViewById(R.id.price);
        buy_num = (EditText) findViewById(R.id.buy_num);
        buy_jian = (ImageView) findViewById(R.id.buy_jian);
        buy_jia = (ImageView) findViewById(R.id.buy_jia);
        sure_buy = (ImageView) findViewById(R.id.sure_buy);
        buy_delete = (ImageView) findViewById(R.id.buy_delete);

        price_grape = findViewById(R.id.price_grape);
        prop_grape_txt = findViewById(R.id.prop_grape_txt);

        buy_jian.setEnabled(false);
        initListener();

        propNum = GetPropLevelUtils.getInstance().getPropNum("葡萄");

        prop_grape_txt.setText("优先使用葡萄币,当前有"+propNum+"个葡萄币.");

        if(daoju.equals("zhandan")) {
            daoju_image.setImageResource(R.drawable.zhandan);
            price.setText("2.0");
            price_grape.setText("100");
            djName = "炸弹道具";
        }else if(daoju.equals("tishi")) {
            daoju_image.setImageResource(R.drawable.tishi);
            price.setText("0.8");
            price_grape.setText("40");
            djName = "提示道具";
        }else if(daoju.equals("times")){
            daoju_image.setImageResource(R.drawable.time);
            price.setText("1.2");
            price_grape.setText("60");
            djName = "时间道具";
        }else if(daoju.equals("xiyou")){
            daoju_image.setImageResource(R.drawable.welcome_xiyou);
            price.setText("1.0");   //一块比50葡萄币//一块比50草莓币
            price_grape.setText("50");
            djName = "体力道具";
        }
    }

    private void initListener() {
        buy_jian.setOnClickListener(this);
        buy_jia.setOnClickListener(this);
        sure_buy.setOnClickListener(this);
        buy_delete.setOnClickListener(this);

        alasbusyIApi = AlasbusyIApi.getInstance(this);
        alasbusyIApi.setHttpQuestResultListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.sure_buy:

                //测试，加入购买成功返回数据
                if(TextUtils.isEmpty(buy_num.getText().toString())){
                    Toasty.warning(PropsBuyActivity.this,"当前购买数量为空.",Toast.LENGTH_SHORT).show();
                    buy_num.setText("1");
                    return;
                }else {
                    /*if (daoju.equals("zhandan")) {
                        Intent intent = new Intent(PropsBuyActivity.this, GameActivity.class);
                        intent.putExtra("num", buy_num.getText().toString());
                        setResult(200, intent);
                        PropsBuyActivity.this.finish();
                    } else if (daoju.equals("tishi")) {
                        Intent intent = new Intent(PropsBuyActivity.this, GameActivity.class);
                        intent.putExtra("num", buy_num.getText().toString());
                        setResult(201, intent);
                        PropsBuyActivity.this.finish();
                    } else if (daoju.equals("times")) {
                        Intent intent = new Intent(PropsBuyActivity.this, GameActivity.class);
                        intent.putExtra("num", buy_num.getText().toString());
                        setResult(202, intent);
                        PropsBuyActivity.this.finish();
                    }else if(daoju.equals("xiyou")){
                        SharedPreferencesUtils.setParam(PropsBuyActivity.this, "xiyou", Integer.parseInt(buy_num.getText().toString()));
                        PropsBuyActivity.this.finish();
                    }*/
                    PropNumPay();
                }

                //应该要打开支付界面进行支付，支付成功再返回购买的数量
                //payV2();
                break;
            case R.id.buy_delete:
                onBackPressed();
                break;
            case R.id.buy_jia:
                int num = Integer.parseInt(buy_num.getText().toString());
                num = num + 1;
                buy_num.setText(String.valueOf(num));
                if(Integer.parseInt(buy_num.getText().toString()) > 1) {
                    buy_jian.setEnabled(true);
                }else {
                    buy_jian.setEnabled(false);
                }
                break;
            case R.id.buy_jian:
                int j_num = Integer.parseInt(buy_num.getText().toString());
                j_num = j_num - 1;
                buy_num.setText(String.valueOf(j_num));
                if(Integer.parseInt(buy_num.getText().toString()) > 1) {
                    buy_jian.setEnabled(true);
                }else {
                    buy_jian.setEnabled(false);
                }
                break;
        }
    }

    public void PropNumPay(){
        num = Integer.parseInt(buy_num.getText().toString());
        if (daoju.equals("zhandan")) {
            useGrapePay(num,100);
            Intent intent = new Intent(PropsBuyActivity.this, GameActivity.class);
            intent.putExtra("num", String.valueOf(num));
            setResult(200, intent);
            PropsBuyActivity.this.finish();
        } else if (daoju.equals("tishi")) {
            useGrapePay(num, 40);
            Intent intent = new Intent(PropsBuyActivity.this, GameActivity.class);
            intent.putExtra("num", String.valueOf(num));
            setResult(201, intent);
            PropsBuyActivity.this.finish();
        } else if (daoju.equals("times")) {
            useGrapePay(num,60);
            Intent intent = new Intent(PropsBuyActivity.this, GameActivity.class);
            intent.putExtra("num", String.valueOf(num));
            setResult(202, intent);
            PropsBuyActivity.this.finish();
        }else if(daoju.equals("xiyou")){
            useGrapePay(num,50);
            //SharedPreferencesUtils.setParam(PropsBuyActivity.this, "xiyou", Integer.parseInt(buy_num.getText().toString()));
            GetPropLevelUtils.getInstance().updatePropNum("西柚", num);
            alasbusyIApi.insertProps(GetPropLevelUtils.getInstance().getUserName(),"西柚", num);
            PropsBuyActivity.this.finish();
        }
    }

    /**
     * 支付宝支付业务
     */
    public void payV2() {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                            //
                            finish();
                        }
                    }).show();
            return;
        }

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
       /* PayTask payTask = new PayTask(this);
        String version = payTask.getVersion();*/
        String time = TimeUtil.getNowYMDHMSTime();
        boolean rsa2 = (ConstactUtil.RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(ConstactUtil.APPID, rsa2,Double.valueOf(price.getText().toString()),"游戏道具",djName,time/*,version*/);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PropsBuyActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = ConstactUtil.SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    public void useGrapePay(int numc,int price){
        propNum = GetPropLevelUtils.getInstance().getPropNum("葡萄");
        prop_grape_txt.setText("优先使用葡萄币,当前有"+propNum+"个葡萄币.");
        if(Integer.parseInt(propNum) >= numc * price) {
            int remaining = Integer.parseInt(propNum) - (numc * price);
            GetPropLevelUtils.getInstance().updatePropNum("葡萄",remaining);
            alasbusyIApi.insertProps(GetPropLevelUtils.getInstance().getUserName(),"葡萄",remaining);
        }else {
            Toasty.warning(PropsBuyActivity.this,"葡萄币不够,将转到第三方支付.",Toast.LENGTH_SHORT).show();
            num = 0;
            //payV2();
        }
    }

    @Override
    public void onBackPressed() {
        if(daoju.equals("zhandan")) {
            Intent intent = new Intent(PropsBuyActivity.this,GameActivity.class);
            intent.putExtra("num", "0");
            setResult(200,intent);
            PropsBuyActivity.this.finish();
        }else if(daoju.equals("tishi")) {
            Intent intent = new Intent(PropsBuyActivity.this,GameActivity.class);
            intent.putExtra("num","0");
            setResult(201,intent);
            PropsBuyActivity.this.finish();
        }else if(daoju.equals("times")) {
            Intent intent = new Intent(PropsBuyActivity.this,GameActivity.class);
            intent.putExtra("num","0");
            setResult(202,intent);
            PropsBuyActivity.this.finish();
        }else if(daoju.equals("xiyou")){
            Intent intent = new Intent(PropsBuyActivity.this,GameActivity.class);
            intent.putExtra("num","0");
            setResult(202,intent);
            PropsBuyActivity.this.finish();
        }
    }

    @Override
    public void onError(Object e) {

    }

    @Override
    public void onSuccess(Object object) {
        if(object instanceof PropsCode) {
            PropsCode propsCode = (PropsCode) object;
            Log.i("KYCC",propsCode.getMessage());
        }
    }

    @Override
    public void onQuestErroCode(Object object) {
        if(object instanceof PropsCode) {
            PropsCode propsCode = (PropsCode) object;
            Toasty.error(PropsBuyActivity.this,propsCode.getMessage()).show();
        }
    }
}
